package com.sita.tingterest.services;

import android.app.Service;
import android.content.Intent;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.sita.tingterest.fragment.FragmentRecommends;
import com.sita.tingterest.pojo.Music;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MusicService extends Service implements MediaPlayer.OnCompletionListener {

    private ArrayList<Music> musicArrayList;
    private SensorManager mSensorManager;
    private MediaPlayer mPlayer;
    private OnMusicEventListener mListener;
    private int mPlayingPosition; // 当前正在播放
    private boolean isShaking;
    private ExecutorService mProgressUpdatedListener = Executors.newSingleThreadExecutor();

    public MusicService() {


    }

    public MusicService(ArrayList<Music> musicArrayLists) {
        super();
        this.musicArrayList = musicArrayLists;
    }

    public void updateMusicList(ArrayList<Music> musicArrayLists) {

        this.musicArrayList = musicArrayLists;
    }

    private final IBinder musicBind = new MyMusicBinder();

    @Override
    public void onCompletion(MediaPlayer mp) {
        Log.i("MY TAG", "MUS onCompletion");
    }

    public class MyMusicBinder extends Binder {
        public MusicService getServices() {
            Log.i("MY TAG", "MusicService MUS");
            return MusicService.this;
        }

    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("MY TAG", "MUS... +onBind");
        // TODO: Return the communication channel to the service.
        return musicBind;
    }

    @Override
    public void onCreate() {
        mPlayer = new MediaPlayer();
        mPlayer.setOnCompletionListener(this);
        // 开始更新进度的线程
        Log.i("MY TAG", "MUS onCreate");
        //  mPlayer=MediaPlayer.create(getApplicationContext(),R.raw.rabta);
        mProgressUpdatedListener.execute(mPublishProgressRunnable);
        mPlayer.setOnBufferingUpdateListener(mBufferUpdateListener);
        super.onCreate();
    }

    private MediaPlayer.OnBufferingUpdateListener mBufferUpdateListener =
            new MediaPlayer.OnBufferingUpdateListener() {
                @Override
                public void onBufferingUpdate(MediaPlayer mp, int percent) {
                    //L.l("percent", percent);
                    Log.i("MY TAG", "MUS percent" + percent);
                    //if (mListener != null) mListener.onPublish(percent);
                }
            };
    private Runnable mPublishProgressRunnable = new Runnable() {
        @Override
        public void run() {
            for (; ; ) {
                Log.i("MY TAG", "MUS mPublishProgressRunnable Enter ");
                if (mPlayer != null && mPlayer.isPlaying() &&
                        mListener != null) {
                    Log.i("MY TAG", "MUS mPublishProgressRunnable IF loop");
                    mListener.onPublish(mPlayer.getCurrentPosition());
                }

                SystemClock.sleep(1000);
            }
        }
    };

    public void setOnMusicEventListener(OnMusicEventListener l) {
        Log.i("MY TAG", "MUS  setOnMusicEventListener");
        mListener = l;
    }

    public int play(int position) {
        if (position < 0) position = 0;
        if (position >= musicArrayList.size())
            position = musicArrayList.size() - 1;

        try {
            mPlayer.reset();
            mPlayer.setDataSource(musicArrayList.get(position).getAudio().getUrl());
            mPlayer.prepare();

            start();
            if (mListener != null) mListener.onChange(position);
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("cav", "" + e);
        }

        mPlayingPosition = position;
        //SpUtils.put(Constants.PLAY_POS, mPlayingPosition);
        return mPlayingPosition;
    }


    public void musicPlay(String url) {
        if (url != null)
            try {
                mPlayer.reset();
                mPlayer.setDataSource(url);
                mPlayer.prepare();
                start();
            } catch (Exception e) {
                e.printStackTrace();
                Log.i("cav", "" + e);
            }
    }

    public int next() {
        if (mPlayingPosition >= FragmentRecommends.musicList.size() - 1) {
            return play(0);
        }

        return play(mPlayingPosition + 1);
    }

    /**
     * 上一曲
     *
     * @return 当前播放的位置
     */
    public int pre() {
        if (mPlayingPosition <= 0) {
            return play(FragmentRecommends.musicList.size() - 1);
        }

        return play(mPlayingPosition - 1);
    }

    public boolean isPlaying() {

        return mPlayer != null && mPlayer.isPlaying();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MY TAG", "MUS onStartCommand");
        return super.onStartCommand(intent, flags, startId);

    }

    public int getCurrentPosition() {

        Log.i("MY TAG", "MUS getCurrentPosition() " + mPlayer.getCurrentPosition());

        return mPlayer.getCurrentPosition();
    }

    public int pausePlayer() {
        //playSong();
        mPlayer.pause();
        Log.i("MY TAG", "MUS pausePlayer() " + mPlayer.getCurrentPosition());
        //Log.v(LOG_TAG, " pausePlayer() position   :" + player.getDuration() +"  == "+mPlayingPosition);

        return mPlayer.getCurrentPosition();

    }

    @Override
    public void onDestroy() {
        release();
        Log.i("MY TAG", "MUS OnDestory");
        super.onDestroy();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        mListener = null;
        Log.i("MY TAG", "MUS onUnbind");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.i("MY TAG", "onRebind MUS");
        super.onRebind(intent);
    }

    public int getDuration() {
        // Log.i("MY TAG","MUS getDuration :"+getDuration());
        if (!isPlaying()) return 0;
        return mPlayer.getDuration();
    }

    public void seek(int msec) {
        Log.i("MY TAG", "MUS seek " + msec);
        if (!isPlaying()) return;
        mPlayer.seekTo(msec);
    }

    /**
     * 开始播放
     */
    public void start() {
        Log.i("MY TAG", "start() MUS");
        mPlayer.start();
    }

    private void release() {
        if (!mProgressUpdatedListener.isShutdown()) mProgressUpdatedListener.shutdownNow();
        mProgressUpdatedListener = null;

        if (mPlayer != null) mPlayer.release();
        mPlayer = null;
    }

    public interface OnMusicEventListener {
        public void onPublish(int percent);

        public void onChange(int position);
    }
}
